import json
from jsontest import Person

"""
对象转成json 


如果json数据中文显示有问题，变成 \uXXX的形式，
原因是中文以变为unicode 编码了，而解码默认是以ASCII解的，中文不在ASCII编码中，
所以无法显示，加上ensure_ascii=False可以防止变为unicode 编码。

避免乱码 ensure_ascii=False 

对象转json ，必须设置 default=lambda obj: obj.__dict__
"""


def test_json_to_str(list1):
    # 对象转成字符串
    s1 = json.dumps(list1, ensure_ascii=False, indent=4, default=lambda obj: obj.__dict__)
    print("对象转字符串", s1)


def test_json_to_file(list1):
    with open("person_list.json", "w") as file:
        json.dump(list1, default=lambda obj: obj.__dict__, ensure_ascii=False, fp=file)
    print("写入文件")


def test_json_file_to_dict():
    with open("person_list.json") as file:
        result = json.load(file)
        print("type", type(result))
        print("result=", result)
        for item in result:
            print(type(item), item)


def object_hook(item):
    return Person(item["name"], item["age"], item["addr"])


# object_hook 钩子函数转成对象
def test_json_file_to_obj():
    with open("person_list.json", ) as file:
        result = json.load(file, object_hook=object_hook)
        print("type", type(result))
        print("result=", result)
        for item in result:
            print(item)
            print(type(item))


if __name__ == '__main__':
    lst = [Person("于吉宽", 20, "郑州高新区"), Person("张小明", 18, "开封杞县")]
    test_json_to_str(lst)
    test_json_to_file(lst)
    test_json_file_to_dict()
    test_json_file_to_obj()
